package com.otitan.la.forest.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.constant.DicEnum;
import com.otitan.la.forest.system.dto.ApplicationDTO;
import com.otitan.la.forest.system.entity.ApplicationEntity;
import com.otitan.la.forest.system.entity.RoleEntity;
import com.otitan.la.forest.system.mapper.ApplicationMapper;
import com.otitan.la.forest.system.service.ApplicationService;
import com.otitan.la.forest.system.service.DicService;
import com.otitan.la.forest.system.service.RoleService;
import com.otitan.la.forest.system.vo.ApplicationEntityVO;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, ApplicationEntity> implements ApplicationService {


    @Autowired
    private DicService dicService;
    @Resource
    private ApplicationMapper applicationMapper;

    @Resource
    private RoleService roleService;

    /**
     * 新增应用
     *
     * @param application, bindingResult
     * @return com.otitan.webapp.framework.basepro.model.DataResult
     * @throws
     * @author Sunke
     * @date 2020/9/17 0017 14:38
     */
    @Override
    public DataResult add(ApplicationEntity application, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<ApplicationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ApplicationEntity::getAppCode, application.getAppCode());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("应用编码不能重复");
        }

        boolean isSuccess = this.save(application);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        LambdaQueryWrapper<RoleEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(RoleEntity::getApplicationId, ids);
        int count = roleService.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("该应用已关联角色，请先取消角色与该应用的关联或删除角色");
        }
        boolean isSuccess = this.removeByIds(ids);
        log.debug("\n>>>>>>>>> 【删除应用表】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, ids);
        return DataResult.success(isSuccess);
    }

    @Override
    public DataResult editor(ApplicationEntity application, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<ApplicationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ApplicationEntity::getAppCode, application.getAppCode());
        queryWrapper.ne(ApplicationEntity::getId, application.getId());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("应用编码不能重复");
        }

        boolean isSuccess = this.updateById(application);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    /**
     * 分页查询应用列表
     *
     * @param page, size, application
     * @return com.otitan.webapp.framework.basepro.model.DataResult
     * @throws
     * @author Sunke
     * @date 2020/9/17 0017 17:44
     */
    @Override
    public DataResult findPageData(long page, long size, ApplicationDTO application) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<ApplicationEntity> queryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotEmpty(application.getCategory())) {
            queryWrapper.eq(ApplicationEntity::getCategory, application.getCategory());
        }
        if (StrUtil.isNotEmpty(application.getType())) {
            queryWrapper.eq(ApplicationEntity::getType, application.getType());
        }
        queryWrapper.orderByAsc(ApplicationEntity::getOrderNo);
        IPage<ApplicationEntity> iPage = this.page(pagePlug, queryWrapper);
        IPage<ApplicationEntityVO> iPageVO = new Page<>();
        BeanUtils.copyProperties(iPage, iPageVO);

        List<ApplicationEntityVO> appListVO = new ArrayList<>();
        if (CollUtil.isNotEmpty(iPage.getRecords())) {
            iPage.getRecords().forEach(app -> {
                ApplicationEntityVO vo = new ApplicationEntityVO();
                BeanUtils.copyProperties(app, vo);
                String categoryName = dicService.getDicName(DicEnum.APP_CATEGORY.getValue(), vo.getCategory());
                vo.setCategoryName(categoryName);
                appListVO.add(vo);
            });
        }
        iPageVO.setRecords(appListVO);
        return DataResult.success(iPageVO);
    }

    @Override
    public DataResult findOne(String id) {
        ApplicationEntity entity = this.getById(id);
        ApplicationEntityVO app = new ApplicationEntityVO();
        BeanUtils.copyProperties(entity, app);
        String categoryName = dicService.getDicName(DicEnum.APP_CATEGORY.getValue(), app.getCategory());
        app.setCategoryName(categoryName);
        return DataResult.success(app);
    }

    @Override
    public DataResult getAppList() {
        LambdaQueryWrapper<ApplicationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.orderByAsc(ApplicationEntity::getOrderNo);
        List<ApplicationEntity> list = applicationMapper.selectList(queryWrapper);
        return DataResult.success(list);
    }

    @Override
    public List<ApplicationEntity> findUserApplicationInfo(String userId) {
        return applicationMapper.findUserApplicationInfo(userId);
    }
}


